package com.pms.web;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.pms.controller.BaseController;
import com.pms.core.CommonConstant;
import com.pms.entity.*;
import com.pms.entity.vo.AuthorityMenuTree;
import com.pms.entity.vo.GroupTree;
import com.pms.entity.vo.GroupUsers;
import com.pms.exception.R;
import com.pms.result.ObjectRestResponse;
import com.pms.rpc.IKyOrganizationRPCService;
import com.pms.rpc.IotGroupAgencyRpcService;
import com.pms.service.*;
import com.pms.util.TreeUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.*;
/**
 * <p>
 *  前端控制器
 * </p>
 * @author zyl
 * @since 2017-07-06
 */
@RestController
@RequestMapping("group")
@Api(value = "角色权限",description = "角色权限")
public class BaseGroupController extends BaseController {

    Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    IBaseGroupService baseGroupService;
    @Autowired
    IBaseResourceAuthorityService baseResourceAuthorityService;
    @Autowired
    IBaseMenuService baseMenuService;
    @Autowired
    IBaseUserService baseUserService;
    @Autowired
    IBaseGroupMemberService baseGroupMemberService;
    @Autowired
    IKyOrganizationRPCService kyOrganizationRPCService;
    @Autowired
    IotGroupAgencyRpcService iotGroupAgencyRpcService;

    /**
     * 编辑角色组归属
     * @param menuType
     * @return
     */
    @PostMapping("/groupByList")
    @ApiOperation("编辑角色组归属")
    @ApiImplicitParams({
            @ApiImplicitParam(name="menuType",value="角色类型",required = true,dataType = "Integer",paramType="form"),
            @ApiImplicitParam(name="id",value="角色组id",required = true,dataType = "Long",paramType="form"),
    })
    public R modifiyMenuAuthority( Integer menuType,Long id){
        parameterIsNull(menuType,"角色类型不能为空");
        parameterIsNull(id,"角色ID不能为空");
        List<Map<String,Object>> list=new ArrayList<>();
        if (menuType.equals(1)){//管网
            list=kyOrganizationRPCService.getGroupOrganizationList(id);
        }else  if (menuType.equals(2)){//二汞
            list=iotGroupAgencyRpcService.getGroupAgencyByRoleIdList(id);
        }else {
            return  R.error(400,"参数异常");
        }
        return  R.ok().put("data",list);
    }

    @RequestMapping(value = "/list")
    @ResponseBody
    public List<BaseGroup> list(String name, String groupType) {
        logger.info("BaseGroupController---->>  list" );
        EntityWrapper entityWrapper = new EntityWrapper();
        if(StringUtils.isNotBlank(name)){
            entityWrapper.eq("name",name);
        }
        if(StringUtils.isNotBlank(groupType)){
            entityWrapper.eq("group_type",groupType);
        }

     List<BaseGroup>baseGroupList=baseGroupService.selectList(entityWrapper);

        return baseGroupList;
    }




    @RequestMapping(value = "/all",method = RequestMethod.GET)
    @ResponseBody
    public List<BaseGroup> list(){
        return baseGroupService.selectList(new EntityWrapper<BaseGroup>());
    }

    @RequestMapping(value = "/{id}/user", method = RequestMethod.PUT)
    @ResponseBody
    public R modifiyUsers(@PathVariable int id, String members, String leaders){
        baseGroupService.modifyGroupUsers(id,members,leaders);
        return R.ok();
    }

    @RequestMapping(value = "/{id}/user", method = RequestMethod.GET)
    @ResponseBody
    public R getUsers(@PathVariable int id){
        GroupUsers groupUsers = baseGroupService.getGroupUsers(id);
        return R.ok().put("date",groupUsers);
    }

       /**
     * 添加权限
     * @param
     * @param menuTrees  菜单ID
     * @return
     */
    @PostMapping("/authority/menu")
    @ApiOperation("添加用户信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name="name",value="角色名称",required = true,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="description",value="描述",required = true,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="menuTrees",value="权限树",required = true,dataType = "String",paramType="form"),
    })
    public R modifiyMenuAuthority(@RequestParam String name,String  description,String menuTrees,Long userId){
        parameterIsBlank(name,"角色名称不能为空");
        parameterIsBlank(description,"描述不能为空");
        parameterIsNull(userId,"用户id不能为空");
        BaseUser user =baseUserService.selectById(userId);
        if (user==null){return  R.error(400,"用户信息不存在");}
        BaseGroup  group=baseGroupService.selectOne(new EntityWrapper<BaseGroup>().eq("name",name).and().eq("company_code",user.getCompanyCode()));
        if (group != null){return  R.error(400,"已存在相应角色名称");}
        BaseGroup entity=new BaseGroup();
        Long id=BaseModel.returnStaticIdLong();
        entity.setId(id);
        entity.setName(name);
        entity.setType(2);
        entity.setCrtUser(getCurrentUserMap().get("userName"));
        entity.setCrtName(getCurrentUserMap().get("userName"));
        entity.setCrtTime(new Date());
        entity.setGroupType(5);
        entity.setCompanyCode(user.getCompanyCode());
        entity.setDescription(description);
        parameterIsBlank(menuTrees,"权限数据不能为空");
        List<AuthorityMenuTree> ae=new ArrayList<AuthorityMenuTree>();
        JSONArray  menuJson =JSONArray.parseArray(menuTrees);
        for (int i=0;i<menuJson.size();i++){
            AuthorityMenuTree ss =new  AuthorityMenuTree();
            JSONObject ade=(JSONObject)menuJson.get(i);
            ss.setId(Integer.parseInt(ade.getString("id")));
            ss.setPermissionsId(ade.getString("baseElementId")+"");
            ae.add(ss);
        }
        baseResourceAuthorityService.modifyAuthorityMenu(id, ae);
        baseGroupService.insert(entity);
        return R.ok();
    }

    /**
     * 修改权限
     * @param
     * @param menuTrees  菜单ID
     * @return
     */
    @PostMapping("/updata/authority/menu")
    @ApiOperation("修改权限")
    @ApiImplicitParams({
            @ApiImplicitParam(name="id",value="角色组id",required = true,dataType = "Long",paramType="form"),
            @ApiImplicitParam(name="name",value="角色名称",required = false,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="description",value="描述",required = false,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="menuTrees",value="权限树",required = false,dataType = "String",paramType="form"),
    })
    public R updataAuthorityMenu(@RequestParam Long id, String name,String  description,String menuTrees){
        parameterIsNull(id,"角色组id不能为空");
        BaseGroup group=baseGroupService.selectById(id);
        if (group==null){return  R.error(400,"角色信息不存在");}
        if (StringUtils.isNotBlank(name)){
            group.setName(name);
        }
        if (StringUtils.isNotBlank(description)){
            group.setDescription(description);
        }
        group.setUpdUser(getCurrentUserMap().get("userName"));
        group.setUpdName(getCurrentUserMap().get("userName"));
        if (StringUtils.isNotBlank(menuTrees)){
       List<AuthorityMenuTree> ae=new ArrayList<AuthorityMenuTree>();
        JSONArray  menuJson =JSONArray.parseArray(menuTrees);
            for (int i=0;i<menuJson.size();i++){
                AuthorityMenuTree aa =new  AuthorityMenuTree();
                JSONObject ade=(JSONObject)menuJson.get(i);
                aa.setId(Integer.parseInt(ade.getString("id")));
                aa.setPermissionsId(ade.getString("baseElementId")+"");
                ae.add(aa);
             }
            baseResourceAuthorityService.modifyAuthorityMenu(id, ae);
        }
        baseGroupService.updateById(group);
        return R.ok();
    }


    @RequestMapping(value = "/{id}/authority/menu", method = RequestMethod.GET)
    @ResponseBody
    public R getMenuAuthority(@PathVariable int id){
        List<AuthorityMenuTree> trees = baseMenuService.getAuthorityMenu(id);
        return R.ok().put("date",trees);
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @ResponseBody
    public ObjectRestResponse<List<AuthorityMenuTree>> findByid(@PathVariable int id){
        return new ObjectRestResponse().data(baseGroupService.selectById(id));
    }

    @RequestMapping(value = "/{id}/authority/element/add", method = RequestMethod.POST)
    @ResponseBody
    public R addElementAuthority(@PathVariable int id, int menuId, int elementId){
        baseResourceAuthorityService.modifyAuthorityElement(id,menuId,elementId);
        return R.ok();
    }

    @RequestMapping(value = "/{id}/authority/element", method = RequestMethod.GET)
    @ResponseBody
    public R  addElementAuthority(@PathVariable int id){
        List<Integer> authList = baseResourceAuthorityService.getAuthorityElement(id);
        return R.ok().put("date",authList);
    }

    /**
     * 树结构  用于角色组管理
     * @param userId
     * @return
     */
    @RequestMapping(value = "/tree", method = RequestMethod.GET)
    @ResponseBody
    public List<GroupTree> tree(String userId) {
//        EntityWrapper entityWrapper = new EntityWrapper();
//        if(StringUtils.isNotBlank(name)){
//            entityWrapper.like("name",name);
//        }
//        if(StringUtils.isNotBlank(groupType)){
//            entityWrapper.like("group_type",groupType);
//        }
        return  getTree(baseGroupService.queryListByGroup(userId), CommonConstant.ROOT);
    }




    /**
     * 用于用户添加角色
     * @param userId
     * @return
     */
    @RequestMapping(value = "/baseGroupList", method = RequestMethod.GET)
    @ResponseBody
    public List<BaseGroup> baseGroup(String userId) {
        return  baseGroupService.queryListByGroup(userId);
    }


    private List<GroupTree> getTree(List<BaseGroup> groups,int root) {
        List<GroupTree> trees = new ArrayList<GroupTree>();
        GroupTree node = null;
        for (BaseGroup group : groups) {
            node = new GroupTree();
            node.setLabel(group.getName());
            BeanUtils.copyProperties(group, node);
            trees.add(node);
        }
        return TreeUtil.bulid(trees,root) ;
    }

    /**
     * 查询该用户的角色权限
     * @return
     */
    @GetMapping(value = "/getGroupList")
    @ApiOperation("查询该用户的角色权限")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "limit", value = "条数", required = true, dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "page", value = "页数", required = true, dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "name", value = "", required = false, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "userId", value = "用户ID", required = true, dataType = "userId", paramType = "form"),
    })
    public R page(int limit,int page, String name,Long userId){
        parameterIsNull(userId,"用户ID不能为空");
        if (limit<1){limit=10;}
        if (page<1){page=1;}
        Page<BaseGroup> pages = new Page<>(page,limit);
        BaseUser user =baseUserService.selectbyPipUser(userId);
        if (user==null){return  R.error(400,"用户信息不存在");}
        Map<String, Object> parameter = new HashMap<>();
        parameter.put("type",user.getType());
        parameter.put("roleType",user.getRoleType());
        if (user.getType()==1){
            parameter.put("companyCode",user.getCompanyCode());
        }else if (user.getType()==2){
            parameter.put("companyCode",user.getCompanyCode());
            parameter.put("groupType","group_type > 1");
        }
        if (StringUtils.isNotBlank(name)){
            parameter.put("name","and (name like binary '%"+name+"%' or crt_user like binary '%"+name+"%'" +
                    "or crt_name like binary '%"+name+"%'or crt_time like binary '%"+name+"%'or upd_user like binary '%"+name+"%'" +
                    "or upd_name like binary '%"+name+"%'or description like binary '%"+name+"%')");
        }
        parameter.put("limit",limit);
        parameter.put("page",(page-1)*limit);
        Page<BaseGroup> pageList = baseGroupService.selectByPageList(pages,parameter);
        return  R.ok().put("data",pageList);
    }





    /**
     * 添加角色权限
     * @param groupId
     * @param userId
     * @return
     */
    @PostMapping("/addGroupMember")
    @ApiOperation("添加用户角色权限")
    @ApiImplicitParams({
            @ApiImplicitParam(name="groupId",value="角色ID",required = true,dataType = "Long",paramType="form"),
            @ApiImplicitParam(name="userId",value="用户ID",required = true,dataType = "Long",paramType="form"),
              })
    public R addGroupMember(Long groupId,Long userId){
        parameterIsNull(groupId,"角色ID不能为空");
        parameterIsNull(userId,"角色ID不能为空");
        BaseGroupMember groupMemberList=baseGroupMemberService.selectOne(new EntityWrapper<BaseGroupMember>().eq("user_id",userId));
        if (groupMemberList!=null){return  R.error(400,"该用户已绑定角色权限请修改");}
        BaseUser user=baseUserService.selectById(userId);
        parameterIsNull(user,"用户信息不存在");
        BaseGroup group=baseGroupService.selectById(groupId);
        parameterIsNull(group,"角色信息不存在");
        BaseGroupMember groupMember=new BaseGroupMember();
        groupMember.setGroupId(groupId.toString());
        groupMember.setCrtTime(new Date());
        groupMember.setUserId(userId.toString());
        baseGroupMemberService.insert(groupMember);
        return  R.ok();
    }

    /**
     * 修改角色权限
     * @param id
     * @param groupId
     * @param userId
     * @return
     */
    @PostMapping("/updataGroupMember")
    @ApiOperation("修改添加用户角色权限")
    @ApiImplicitParams({
            @ApiImplicitParam(name="id",value="用户角色ID",required = true,dataType = "Integer",paramType="form"),
            @ApiImplicitParam(name="groupId",value="角色ID",required = true,dataType = "Long",paramType="form"),
            @ApiImplicitParam(name="userId",value="用户ID",required = true,dataType = "Long",paramType="form"),
    })
    public R updataGroupMember(Integer id,Long groupId,Long userId){
        parameterIsNull(id,"用户角色ID不能为空");
        parameterIsNull(groupId,"角色ID不能为空");
        parameterIsNull(userId,"角色ID不能为空");
        BaseGroupMember groupMember= baseGroupMemberService.selectById(id);
        parameterIsNull(groupMember,"用户角色信息不存在");
        BaseUser user=baseUserService.selectById(userId);
        parameterIsNull(user,"用户信息不存在");
        BaseGroup group=baseGroupService.selectById(groupId);
        parameterIsNull(group,"角色信息不存在");
        groupMember.setGroupId(groupId.toString());
        groupMember.setUpdTime(new Date());
        groupMember.setUserId(userId.toString());
        baseGroupMemberService.updateById(groupMember);
        return  R.ok();
    }



    /**
     * 删除角色组
     * @param id
     * @return
     */
    @GetMapping(value = "/delete/id")
    @ApiOperation("删除角色组")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "角色组ID", required = true, dataType = "Long", paramType = "form"),
    })
    public R delete(Long id){
        parameterIsNull(id,"角色组id不能为空");
        BaseGroup group=baseGroupService.selectById(id);
        if (group==null){return  R.error(400,"角色信息不存在");}
        if (group.getType()!=2){return  R.error(400,"不能删除默认角色");}
        //删除角色管网分区关联
        kyOrganizationRPCService.deleteGroupOrganization(id);
        //删除角色二汞机构关联
        iotGroupAgencyRpcService.delGroupAgencyByRoleId(id);
        //删除角色权限
        baseResourceAuthorityService.delete(new EntityWrapper<BaseResourceAuthority>().eq("authority_id",id));
        //删除角色用户权限
        baseGroupMemberService.delete(new EntityWrapper<BaseGroupMember>().eq("group_id",id));
        //删除角色
        baseGroupService.deleteById(id);
        return R.ok();
    }


    /**
     * 编辑角色组
     * @return
     */
    @GetMapping(value = "/getBygroupElement")
    @ApiOperation("编辑角色组")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "menuType", value = "菜单类型", required = true, dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "groupId", value = "角色组ID", required = true, dataType = "userId", paramType = "form"),
    })
    public R getBygroupElement(@RequestParam  int  menuType,Long groupId){
        parameterIsNull(menuType,"菜单类型不能为空");
        parameterIsNull(groupId,"角色组id不能为空");
        if (menuType==0){
            menuType=3;
        }
        Map<String,Object> map=new HashMap<>();
        BaseGroup group=baseGroupService.selectById(groupId);
        if (group==null){
            return R.error(400,"角色信息不存在");
        }
        if (group.getGroupType()==4){//表示是浏览者
            group.setType(2);
        }
        List<Map<String,Object>> maps =baseGroupService.getBygroupElement(menuType,groupId,group.getType());
        map.put("list",maps);
        map.put("group",group);
        return R.ok().put("data",map);
    }

}
